/**
 * Ingenius-Group S.A.S
 *
 * Project: SAU
 * File: LoginCheck.java
 * Date: 27/03/2011
 */

package com.ingenius.sau.server.security;

import java.util.ArrayList;
import java.util.List;

import org.securityfilter.realm.SimpleSecurityRealmBase;

import com.ingenius.sau.server.persistence.RoleDAO;
import com.ingenius.sau.server.persistence.UserDAO;
import com.ingenius.sau.server.persistence.jdo.JdoRoleDAO;
import com.ingenius.sau.server.persistence.jdo.JdoUserDAO;
import com.ingenius.sau.shared.model.users.Role;
import com.ingenius.sau.shared.model.users.User;

/**
 * Class <strong>LoginCheck</strong>
 * 
 * @author Jesus David
 * @version 0.1
 */
public class LoginCheck extends SimpleSecurityRealmBase {

	private UserDAO userDAO = new JdoUserDAO();
	private RoleDAO roleDAO = new JdoRoleDAO();

	/**
	 * Authenticate a user.
	 * 
	 * Implement this method in a subclass to avoid dealing with Principal
	 * objects.
	 * 
	 * @param username
	 *            a username
	 * @param password
	 *            a plain text password, as entered by the user
	 * 
	 * @return null if the user cannot be authenticated, otherwise a Principal
	 *         object is returned
	 */
	public boolean booleanAuthenticate(String username, String password) {
		try {
			if (userDAO.count(null) == 0) {
				createDefaultUser();
			}

		} catch (Exception e) {
			System.out.println("Error creating default user");
		}
		return userDAO.authenticate(username, password);
	}

	/**
	 * Test for role membership.
	 * 
	 * Implement this method in a subclass to avoid dealing with Principal
	 * objects.
	 * 
	 * @param username
	 *            The name of the user
	 * @param role
	 *            name of a role to test for membership
	 * @return true if the user is in the role, false otherwise
	 */
	public boolean isUserInRole(String username, String role) {
		// test role, disable it
		if (username.equals("admin")) {
			return true;
		}
		boolean result = (userDAO.userFor(username) != null) ? true : false;
		return result && "admin".equals(role);
	}

	private void createDefaultUser() throws Exception {
		List<String> privileges = new ArrayList<String>();
		privileges.add("users.create=yes");
		privileges.add("users.edit=yes");
		privileges.add("users.read=yes");
		privileges.add("users.delete=yes");

		Role role = new Role();
		role.setName("Administrator");
		role.setDescription("Administrator");
		role.setPrivileges(privileges);
		roleDAO.save(role);

		User user = new User();
		user.setUsername("admin");
		user.setPassword("admin");
		user.setPasswordChangeRequired(true);
		user.setRole(role);
		userDAO.save(user);
	}

}
